<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="theme-color" content="#222">

<script>
    (function(){
        if('https://huangguangda.github.io/'){
            if (prompt('请输入文章密码') !== 'https://huangguangda.github.io/'){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/6f697dad.js","daovoice")
  daovoice('init', {
      app_id: "6f697dad"
    });
  daovoice('update');
  </script>















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="我的视频,">





  <link rel="alternate" href="/atom.xml" title="达叔小生" type="application/atom+xml">






<meta name="description" content="用一切抱怨的时间去努力">
<meta name="keywords" content="我的视频">
<meta property="og:type" content="article">
<meta property="og:title" content="零基础入门Android语法与界面笔记">
<meta property="og:url" content="https://huangguangda.github.io/2018/05/08/1/index.html">
<meta property="og:site_name" content="达叔小生">
<meta property="og:description" content="用一切抱怨的时间去努力">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://huangguangda.github.io/images/83.jpg">
<meta property="og:updated_time" content="2018-07-01T06:11:04.634Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="零基础入门Android语法与界面笔记">
<meta name="twitter:description" content="用一切抱怨的时间去努力">
<meta name="twitter:image" content="https://huangguangda.github.io/images/83.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangguangda.github.io/2018/05/08/1/">




<!-- 网页加载条 -->
<script src="https://neveryu.github.io/js/src/pace.min.js"></script>
  <title>零基础入门Android语法与界面笔记 | 达叔小生</title>
  









  <!-- 音频播放 -->
<link rel="stylesheet" href="/dist/APlayer.min.css">
<div id="aplayer"></div>
<script type="text/javascript" src="/dist/APlayer.min.js"></script>
<script type="text/javascript" src="/dist/music.js"></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <a href="https://github.com/huangguangda" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">达叔小生</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">爱好分享的码农</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-首页">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-关于">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-标签">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-分类">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-归档">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-书籍">
          <a href="/books" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br>
            
            书籍
          </a>
        </li>
      
        
        <li class="menu-item menu-item-电影">
          <a href="/movies" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-chrome"></i> <br>
            
            电影
          </a>
        </li>
      
        
        <li class="menu-item menu-item-站点">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>
            
            站点
          </a>
        </li>
      
        
        <li class="menu-item menu-item-公益">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益
          </a>
        </li>
      
        
        <li class="menu-item menu-item-课本">
          <a href="/book/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-apple"></i> <br>
            
            课本
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangguangda.github.io/2018/05/08/1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="达叔小生">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="达叔小生">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">零基础入门Android语法与界面笔记</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-08T20:08:15+08:00">
                2018-05-08
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/我的视频/" itemprop="url" rel="index">
                    <span itemprop="name">我的视频</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  10,151
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  39
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center">用一切抱怨的时间去努力</blockquote>

<p><img src="/images/83.jpg" style="width: 100%;height: 100%"></p>
<a id="more"></a>
<p>来源零基础入门Android语法与界面做笔记</p>
<p>面向对象</p>
<p>1、什么是对象<br>2、什么是面向对象<br>3、什么是类<br>4、什么是属性<br>5、什么是方法<br>6、类和对象的关系</p>
<p>什么是对象<br>•   万物皆对象、客观存在的事物<br>•   对象：用来描述客观事物的一个实体，由一组属性和方法构成</p>
<p>什么是面向对象<br>•   人关注对象<br>•   人关注事物信息</p>
<p>类<br>•   类是模子，确定对象将会拥有的特征（属性）和行为（方法）<br>•   类的特点<br>•   类是对象的类型<br>•   具有相同属性和方法的一组对象的集合</p>
<p>什么是对象的属性和方法<br>•   属性：对象具有的各种静态特征<br>•   “有什么”<br>•   方法：对象具有的各种动态行为<br>•   “能做什么”</p>
<p>类和对象的关系<br>•   类是抽象的概念，仅仅是模板<br>•   对象是一个你能够看得到、摸得着的具体实体<br>•   类是对象的类型<br>•   对象是特定类型的数据<br>•   具体开发过程中，先定义类再实例化对象</p>
<p>单一职责原则<br>•   单一职责原则，也称为单一功能原则<br>•   英文Single Responsibility Principle 缩写SRP<br>•   是面向对象设计中的一个重要原则<br>•   一个类，应该有且只有一个引起变化的原因<br>•   在程序设计中，尽量把不同的职责，放在不同的职责中，即把<br>不同的变化原因，封装到不同的类中。</p>
<p>对象实例化需要了解的</p>
<p>对象实例化<br>•   实例化对象的过程可以分为两部分：<br>–  声明对象   Cat one<br>–  实例化对象   new Cat();<br>–  Cat one=new Cat();</p>
<p>对象实例化<br>•   每次new对象会产生新的实例化对象<br>–  Cat one=new Cat();<br>–  Cat two=new Cat();</p>
<p>对象实例化<br>•   多个对象可以指向同一块实例化空间<br>–  Cat one=new Cat();<br>–  Cat two=one;</p>
<p>对象实例化<br>•   对象必须被实例化之后才能使用<br>•   对象间的引用传递，实际上传递的是堆内存空间的使用权</p>
<p>构造方法<br>1、构造方法与类同名且没有返回值<br>2、构造方法的语句格式<br>3、只能在对象实例化的时候调用</p>
<p>构造方法<br>4、当没有指定构造方法时，系统会自动添加无参的构造方法<br>5、当有指定构造方法，无论是有参、无参的构造方法，都不会自<br>动添加无参的构造方法<br>6、一个类中可以有多个构造方法</p>
<p>单一职责原则（SRP：Single responsibility principle）又称单一功能原<br>则，面向对象五个基本原则（SOLID：  SRP 单一责任原则、OCP  开放封闭原<br>则、LSP 里氏替换原则、DIP 依赖倒置原则、ISP  接口分离原则）之一。它规<br>定一个类应该只有一个发生变化的原因。该原则由罗伯特·C·马丁（Robert C.<br>Martin）于《敏捷软件开发：原则、模式和实践》一书中给出的。马丁表示此<br>原则是基于汤姆·狄马克(Tom DeMarco)和 Meilir Page-Jones  的著作中的内<br>聚性原则发展出的。</p>
<p>所谓职责是指类变化的原因。如果一个类有多于一个的动机被改变，那么<br>这个类就具有多于一个的职责。而单一职责原则就是指一个类或者模块应该有<br>且只有一个改变的原因。</p>
<p>单一职责原则告诉我们：一个类不能太“累”！在软件系统中，一个类<br>（大到模块，小到方法）承担的职责越多，它被复用的可能性就越小，而且一<br>个类承担的职责过多，就相当于将这些职责耦合在一起，当其中一个职责变化<br>时，可能会影响其他职责的运作，因此要将这些职责进行分离，将不同的职责<br>封装在不同的类中，即将不同的变化原因封装在不同的类中，如果多个职责总<br>是同时发生改变则可将它们封装在同一类中。</p>
<p>之所以会出现单一职责原则就是因为在软件设计时会出现以下类似场景：T<br>负责两个不同的职责：职责 P1，职责 P2。当由于职责 P1  需求发生改变而需要<br>修改类 T P2  功能发生故障。也就是说<br>职责 P1 和 P2<br>解决办法：遵守单一职责原则，将不同的职责封装到不同的类或模块中。<br>分别建立两个类 T1、T2，使 T1 完成职责 P1 功能，T2 完成职责 P2  功能。这<br>样，当修改类 T1 时，不会使职责 P2 发生故障风险；同理，当修改 T2  时，也<br>不会使职责 P1  发生故障风险。</p>
<p>关键字的用法</p>
<p>this 在类中就是代表当前对象，可以通过 this  关键字完成当前<br>对象的成员属性、成员方法和构造方法的调用。<br>那么何时用 this？<br>当在定义类中的方法时，如果需要调用该类对象，就可以用  this<br>来表示这个对象。也就是说，但凡在本类功能内部使用到了本类对象，<br>都用 this  表示。至于代表哪个对象，就看其所在功能被哪个对象调<br>用，这样就知道谁在参与运算。</p>
<p>封装<br>•   将类的某些信息隐藏在类内部，不允许外部程序直接访问<br>•   通过该类提供的方法来实现对隐藏信息的操作和访问<br>•   隐藏对象的信息<br>•   留出访问的接口</p>
<p>封装<br>特点：<br>1、只能通过规定的方法访问数据<br>2、隐藏类的实例细节，方便修改和实现</p>
<p>封装<br>设为private<br>修改属性的可见性<br>设为public<br>创建getter/setter方法<br>用于属性的读写<br>对属性值的合<br>法性进行判断<br>在getter/setter方法中加<br>入属性控制语句</p>
<p>包<br>作用：<br>1、管理Java文件<br>2、解决同名文件冲突</p>
<p>定义包<br>语法：<br>package 包名;<br>例：package com.imooc.animal;<br>注意：<br>1、必须放在Java源文件中的第一行<br>2、一个Java源文件中只能有一个package语句<br>3、包名全部英文小写<br>4、命名方式：域名倒序+模块+功能</p>
<p>导入包<br>语法：<br>import 包名.类名;<br>例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">导入包中全部类：</span><br><span class="line">import com.imooc.*;</span><br><span class="line">导入包中指定类：</span><br><span class="line">import com.imooc.animal.Cat;</span><br></pre></td></tr></table></figure></p>
<p>常用系统包<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">java.lang   包含java语言基础的类</span><br><span class="line">java.util     包含java语言中各种工具类</span><br><span class="line">java.io       包含输入、输出相关功能的类</span><br></pre></td></tr></table></figure></p>
<p>static<br>1、static+属性—静态属性<br>2、static+方法—静态方法<br>3、static+类—不存在<br>4、static+方法内局部变量—不存在<br>静态成员随类加载产生，直至类销毁才回收</p>
<p>静态方法<br>1、可以直接调用同类中的静态成员<br>2、不可以直接调用同类中的非静态成员<br>3、可以通过实例化对象后，对象调用的方式完成非静态成员调用</p>
<p>代码块<br>1、通过{ }可以形成代码块<br>2、方法内的代码块称为：普通代码块<br>3、类内的代码块称为：构造代码块<br>4、构造代码块前+static：静态代码块</p>
<p>代码块执行顺序<br>1、无论实例产生多少对象，静态代码块只执行一次<br>2、构造代码块随实例化过程调用<br>3、普通代码块随方法调用执行</p>
<h2 id="kage-和-import-的使用"><a href="#kage-和-import-的使用" class="headerlink" title="kage 和 import 的使用"></a>kage 和 import 的使用</h2><p>1、打包–package<br>包名一般为小写，而类名的第一个字母一般为大写，这样在引用时，可以明显的分<br>辨出包名和类名。如果在类的定义之前没有使用package定义包名，那么该类就属于缺<br>省的包。</p>
<p>1.1、包的作用<br>可以更好的组织类，包与文件夹类似，文件夹可以将不同的文件放在同一个文件夹<br>中，而包也可以将不同的类文件放在同一包中。<br>减少类名的冲突问题，这也与文件夹类似，同一文件夹中的文件不能重名，不同文<br>件中的 文件可以重名，同一包中的类名不能重复，不同包中的类名可以重复。<br>对包中的类起了一定的保护作用，详见 Java  的访问控制（在后面的课程中会详细<br>讲解~~）。</p>
<p>1.2、包的使用<br>使用 package 关键字指明类所在的包。 package 语句必须在文件的最前面。 编译<br>时可使用 javac –d . Test.java 自动产生包需要目录。 可以使用 java testPackage.Test<br>来执行编译后的代码。</p>
<p>2、导入–import<br>使用了包机制后，如果在一个类中使用了其他包中的类，需要使用 import  来引入。</p>
<p>2.1 import的使用<br>直接引用指定的类，如 import java.util.Vector。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">引用一个包中的多个类，如 import java.awt.*。*号代替类名，但不能代替包名，如</span><br><span class="line">import java.awt.*，只引用 java.awt 下的类，而不引用 java.awt  下的子包里面的类。</span><br><span class="line">import java.awt.F*，这种使用方法是错误的。</span><br><span class="line">import 语句在所有类定义之前，在 package 定义之后。import  只告诉编译器及解</span><br><span class="line">释器哪里可以找到类、变量、方法的定义，而并没有将这些定义 引入代码中。</span><br><span class="line">2.2  包中类的使用</span><br><span class="line">如果要使用的类是属于 java.lang  包的，那么可以直接使用类名来引用指定的类，而</span><br><span class="line">不需要加上包名，因为包 java.lang 不用显示使用 import，它是缺省引入的。 如果要使</span><br><span class="line">用的类在其它包（java.lang 除外）中，那么可以通过包名加上类名来引用该类， 如</span><br><span class="line">java.awt.Font。</span><br><span class="line">对于经常要使用的类（该类在其它包中），那么最好使用 import  引用指定的包，如</span><br><span class="line">java.awt.*。</span><br><span class="line">如果 import  引入的不同的包中包含有相同的类名，那么这些类的使用必须加上包名。</span><br></pre></td></tr></table></figure>
<p>生活中的继承<br>•   孩子像爸妈<br>•   富二代<br>•   师徒关系</p>
<p>程序中的继承<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">-表示私有</span><br><span class="line">Dog</span><br><span class="line">- name:String</span><br><span class="line">- month:int</span><br><span class="line">- species:String</span><br><span class="line">- sex:String</span><br><span class="line">- name:String</span><br><span class="line">- month:int</span><br><span class="line">- species:String</span><br><span class="line">- weight:double</span><br></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">+表示公有</span><br><span class="line">+ eat():void</span><br><span class="line">+ eat():void</span><br><span class="line">+ getName():String</span><br><span class="line">+ getMonth ():int</span><br><span class="line">+ getSpecies ():String</span><br><span class="line">+ getSex():String</span><br><span class="line">+ sleep():void</span><br><span class="line">+ getName():String</span><br><span class="line">+ getMonth ():int</span><br><span class="line">+ getSpecies ():String</span><br><span class="line">+ getWeight():double</span><br><span class="line">+ run():void</span><br><span class="line">+ Dog()</span><br><span class="line">+ Cat()</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">程序中的继承</span><br><span class="line">Cat</span><br><span class="line">Dog</span><br><span class="line">Animal</span><br><span class="line">- sex:String</span><br><span class="line">+ sleep():void</span><br><span class="line">+ Dog()</span><br><span class="line">- weight:double</span><br><span class="line">- name:String</span><br><span class="line">- month:int</span><br><span class="line">- species:String</span><br><span class="line">+ run():void</span><br><span class="line">+ Cat()</span><br><span class="line">+ eat():void</span><br><span class="line">+ getName():String</span><br><span class="line">+ getMonth ():int</span><br><span class="line">+ getSpecies ():String</span><br><span class="line">+ getWeight():double</span><br></pre></td></tr></table></figure>
<p>继承<br>特点：<br>1、利于代码复<br>2、缩短开发周期</p>
<p>继承<br>•  一种类与类之间的关系<br>•  使用已存在的类的定义作为基础建立新类<br>•  新类的定义可以增加新的数据或新的功能，也可以用父类的<br>功能，但不能选择性地继承父类<br>•父类 基类<br>•子类 派生类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">继承的关系</span><br><span class="line">• 满足“A is a B  ”的关系就可以形成继承关系</span><br><span class="line">如：</span><br><span class="line">猫、狗是动物==》猫，狗继承自动物</span><br><span class="line">学生、老师是人==》学生，老师继承自人</span><br><span class="line">小轿车、大卡车是汽车==》小轿车，大卡车继承自汽车</span><br></pre></td></tr></table></figure>
<p>实现继承<br>使用extends实现封装<br>–编写父类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">class Animal&#123;</span><br><span class="line">//公共的属性和方法</span><br><span class="line">&#125;</span><br><span class="line">–编写子类，继承父类</span><br><span class="line">class Dog extends  Animal&#123;</span><br><span class="line">//子类特有的属性和方法</span><br><span class="line">&#125;</span><br><span class="line">class Cat extends  Animal&#123;</span><br><span class="line">&#125;</span><br><span class="line">只能继承一个父类</span><br></pre></td></tr></table></figure></p>
<p>方法重写<br>语法规则：<br>•  返回值类型<br>•  方法名<br>•  参数类型、顺序、个数<br>都要与父类继承的方法相同</p>
<p>方法重写 PK  方法重载<br>•   方法重写：<br>•   方法重载：<br>–  在满足继承关系的子类中<br>–  在同一个类中<br>–  方法名相同<br>–  方法名、参数个数、顺序、类型与<br>父类、返回值相同<br>–  参数个数、顺序、类型不同<br>–  返回值类型、访问修饰符任意<br>–  访问修饰符的限定范围大于等于<br>父类方法</p>
<p>方法重写存在<br>属性重写不存在</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">访问修饰符</span><br><span class="line">•   公有的：public</span><br><span class="line">•   私有的：private</span><br><span class="line">•   受保护的 ：protected</span><br><span class="line">•   默认</span><br></pre></td></tr></table></figure>
<p>如何区分调用的是继承父类的方法<br>还是子类自己重写的方法？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">super</span><br><span class="line">•   子类访问父类成员</span><br><span class="line">–   访问父类成员方法</span><br><span class="line">super.print();</span><br><span class="line">super.name;</span><br><span class="line">–   访问父类属性</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">实例化顺序</span><br><span class="line">•继承后的初始化顺序</span><br><span class="line">父类静态成员</span><br><span class="line">子类静态成员</span><br><span class="line">父类对象构造</span><br><span class="line">（属性（赋值）、构造代码块、构造方法）</span><br><span class="line">子类对象构造</span><br><span class="line">（属性（赋值）、构造代码块、构造方法）</span><br></pre></td></tr></table></figure>
<p>子类对象实例化时，能否选择父类的构造<br>形式（调用指定的构造方法）？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">super</span><br><span class="line">•   子类访问父类成员</span><br><span class="line">–   访问父类成员方法</span><br><span class="line">super.print();</span><br><span class="line">super.name;</span><br><span class="line">super();</span><br><span class="line">–   访问父类属性</span><br><span class="line">–   访问父类构造方法</span><br></pre></td></tr></table></figure>
<p>super<br>•   子类的构造的过程中必须调用其父类的构造方法<br>•   如果子类的构造方法中没有显示调用父类的构造方法，则系统<br>系默认调用父类无参的构造方法<br>•   如果子类构造方法中既没有显式调用父类的构造方法，而父类<br>又没有无参的构造方法，则编译出错<br>•   使用super调用父类指定构造方法，必须在子类的构造方法的<br>第一行</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">super pk this</span><br><span class="line">•   this:  当前类对象的引用</span><br><span class="line">–   访问当前类的成员方法</span><br><span class="line">–   访问当前类的成员属性</span><br><span class="line">–   访问当前类的构造方法</span><br><span class="line">–   不能在静态方法中使用</span><br><span class="line">•   super:  父类对象的引用</span><br><span class="line">–   访问父类的成员方法</span><br><span class="line">–   访问父类的成员属性</span><br><span class="line">–   访问父类的构造方法</span><br><span class="line">–   不能在静态方法中使用</span><br><span class="line">•   构造方法调用时，super和this不能同时出现</span><br></pre></td></tr></table></figure>
<p>设计模式<br>•   设计模式（Design pattern）是一套被反复使用、多数人知晓的、<br>经过分类编目的、代码设计经验的总结。<br>•   设计模式是软件开发人员在软件开发过程中面临的一般问题的解决<br>方案。</p>
<p>设计模式<br>•   项目中合理的运用设计模式可以完美的解决很多问题<br>•   每种模式在现在中都有相应的原理来与之对应<br>•   每一个模式描述了一个在我们周围不断重复发生的问题，以及该问题<br>的核心解决方案</p>
<p>设计模式<br>•   面向对象的设计模式很多，但大家认为这23个模式是其它模式的基础</p>
<p>单例模式（Singleton）<br>•   滚滚历史，朝代更迭，永恒定律：<br>–  一个朝代皇帝只有一个<br>–  军队的最高司令官只有一个<br>–  一山不容二虎<br>•   计算机系统：<br>–   驱动程序<br>–   打印机后台处理程序（Printer Spooler）<br>–   线程池<br>–   缓存<br>–   日志</p>
<p>单例模式（Singleton）<br>目的：<br>使得类的一个对象成为该类系统中的唯一实例<br>定义：<br>一个类有且仅有一个实例，并且自行实例化向整个系统提供</p>
<p>单例模式<br>要点：<br>1、某个类只能有一个实例<br>2、必须自行创建实例<br>3、必须自行向整个系统提供这个实例<br>实现：<br>1、只提供私有的构造方法<br>2、含有一个该类的静态私有对象<br>3、提供一个静态的公有方法用于创建、获取静态私有对象</p>
<p>单例模式<br>代码实现方案：<br>1、饿汉式<br>2、懒汉式</p>
<p>饿汉式 PK  懒汉式<br>1、饿汉式在类加载时就创建实例， 第一次加载速度快；<br>懒汉式第一次使用时才进行实例化，第一次加载速度慢<br>饿汉式：空间换时间<br>懒汉式：时间换空间<br>2、饿汉式线程安全；懒汉式存在线程风险<br>解决方案：<br>1、同步锁<br>3、静态内部类<br>4、枚举<br>2、双重校验锁</p>
<p>单例模式<br>优点：<br>1、在内存中只有一个对象，节省内存空间<br>2、避免频繁的创建销毁对象，提高性能<br>3、避免对共享资源的多重占用<br>缺点：<br>1、扩展比较困难<br>2、如果实例化后的对象长期不利用，系统将默认为垃圾进行回收，<br>造成对象状态丢失</p>
<p>单例模式<br>适用场景：<br>1、创建对象时占用资源过多，但同时又需要用到该类对象<br>2、对系统内资源要求统一读写，如读写配置信息<br>3、当多个实例存在可能引起程序逻辑错误，如号码生成器</p>
<p>UML  中表示类与类的关系</p>
<p>UML(Unified Modeling Language), 又称统一建模语言或标准建模语言，它是一个支持模型化和软件系统开发的图形化语言，为软件开发的所有阶段提供模型化和可视化支持，可用于多种类型软件系统开发建模的各个阶段。我们可以用 UML  图例来表示类与类之间的<br>各种关系。</p>
<p>类的层次结构代表类与类之间的关系，类的关系有很多种，包括泛化、依赖、关联、聚<br>合和组合。这些关系在大的类别上还可分为两种：横向关系和纵向关系，纵向关系就是泛化关系，而横向关系就是剩下的 4 种，</p>
<p>它们的强弱关系：依赖 &lt;  关联  &lt; 聚合  &lt;  组合。</p>
<p>理解这些类的关系，并应用于类的层次结构设计中，有助于优化代码组织结构。</p>
<p>接下来我们用 Enterprise Architect 12.0.1210 Corporate Edition  建模软件为大家演示这几种类与类关系的表示。</p>
<ol>
<li>泛化</li>
</ol>
<p>泛化关系就是继承，表示一般与特殊的关系，即“一般”元素是“特殊”元素的泛<br>化。在继承中，一般类就是父类，特殊类就是子类。</p>
<p>它们之间是“is a”的关系。</p>
<p>如：一个 Cat 类继承 Animal 类，也就是说 Cat is an Animal。在 UML类图设计中，继承用一条带空心三角箭头的实线表示，从子类指向父类，或者子接口指向父<br>接口。</p>
<ol start="2">
<li>依赖</li>
</ol>
<p>表示一个元素以某种方式依赖于另一种元素。</p>
<p>依赖就是一个类 A 使用到了另一个类B，而这种使用关系是具有偶然性的、临时性的、非常弱的，但是类 B  的变化会影响到类 A。</p>
<p>它们之间是“use a”的关系。</p>
<p>依赖的例子有：一个类把另一个类的对象作为参数，一个类访问另一个类的全局变<br>量，或者一个类调用另一个类的类操作。</p>
<p>比如某人要过河，需要借用一条船，此时人与船之间的关系就是依赖。表现在代码<br>层面，为类 B 作为参数被类 A 在某个 method 方法中使用。在 UML  类图设计中，依赖关系用由类 A 指向类 B  的带箭头虚线表示。</p>
<ol start="3">
<li>关联</li>
</ol>
<p>关联体现的是两个类之间一种强依赖关系，这种关系比依赖更强、不存在依赖关系<br>的偶然性、关系也不是临时性的，一般是长期性的，而且双方的关系一般是平等的。<br>关联可以是单向、双向的。</p>
<p>比如老师和学生是双向关联，老师有多名学生，学生也可能有多名老师。学生跟学<br>生学号之间是单向关联，一个学生只能对应一个唯一的学号。在 UML  类图设计中,  双向的关联可以有两个箭头或者没有箭头，单向的关联有一个箭头。</p>
<ol start="4">
<li>聚合</li>
</ol>
<p>聚合关系是关联关系的一种，是强的关联关系，它体现的是整体与部分的关系  ，<br>且部分可以离开整体而单独存在；关联和聚合在语法上无法区分，必须考察具体的<br>逻辑关系。</p>
<p>它们之间是“use a”的关系。<br>此时整体与部分之间是可分离的，它们可以具有各自的生命周期，部分可以属于多<br>个整体对象，也可以为多个整体对象共享。</p>
<p>在 UML  类图设计中，聚合关系以空心菱形加实线表示。如学校有很多老师。</p>
<ol start="5">
<li>组合</li>
</ol>
<p>是整体与部分的关系，是比聚合关系还要强的关系，但此时整体与部分是不可分的，整体的生命周期结束也就意味着部分的生命周期结束，如公司和部门是整体和部分的关系,  没有公司就不存在部门。</p>
<p>它体现的是一种“contains-a”的关系。<br>在 UML  类图设计中，组合关系以实心菱形加实线表示。</p>
<p>抽象类和抽象方法</p>
<p>一：知识梳理</p>
<p>1.基本概念：</p>
<p>在面向对象的概念中，所有的对象都是通过类来描述的，但并不是说所有的类都是用<br>来描述对象的，当一个类中没有包含足够的信息以描绘一个具体的对象时，这样的类<br>就是抽象类。</p>
<p>例：形状就是一个抽象的概念。不同的子类计算形状面积的方法是不一样的。可提供<br>抽象方法来被不同的子类所实现。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape&#123;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从例子中可看出，抽象类是用关键字 abstract   修饰的。抽象类中有一种特殊方法，即用 abstract 关键字来修饰的方法，称为“抽象方法”。</p>
<p>2.抽象类和抽象方法的声明格式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">abstract class &lt;类名&gt;&#123;</span><br><span class="line">	成员变量;</span><br><span class="line">	方法（）&#123;方法体&#125;;</span><br><span class="line">    abstract 方法（）；</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>3.抽象类和抽象方法的特点：</p>
<p>（1）抽象方法不允许直接实例化，换句话说抽象类不能创建对象，它只能作为其他类的父类。  但可以通过向上转型，指向实例化。</p>
<p>（2）抽象方法只有声明，不能有实现，也就是仅有方法头，而没有方法体和操作实现。</p>
<p>如：abstract double area( );</p>
<p>4.定义抽象类的意义在于：</p>
<p>（1）为其子类提供一个公共的类型（父类引用指向子类对象）；<br>（2）封装子类中的重复内容（成员变量和方法）;<br>（3）将父类设计成抽象类后，既可借由父子继承关系限制子类的设计随意性，在一定程度上避免了无意义父类的实例化。</p>
<p>二．重点注意</p>
<p>含有抽象方法的类，只能被定义成抽象类。</p>
<p>如下面，不定义为抽象类时会报错：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public class Shape&#123;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>正确的代码为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape()&#123;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>抽象类不一定包含抽象方法。<br>例子：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape&#123;</span><br><span class="line">	public void girth()&#123;</span><br><span class="line">		System.out.println(&quot;图形周长为...&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在抽象类中的成员方法可以包括一般方法和抽象方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape&#123;</span><br><span class="line">	public void girth()&#123;</span><br><span class="line">		System.out.println(&quot;图形周长为..&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>抽象类不能被实例化，即使抽象类里不包含抽象方法，这个抽象类也不能创建实例。<br>抽象类的构造方法主要是用于被其子类调用。</p>
<p>例子：<br>Shape  抽象类中不含抽象方法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape&#123;</span><br><span class="line">	public void girth()&#123;</span><br><span class="line">		System.out.println(&quot;图形周长为..&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>测试类中实例化 Shape,编译器会报错：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Shape s=new Shape();</span><br></pre></td></tr></table></figure></p>
<p>一个类继承抽象类后，必须实现其所有抽象方法，否则也是抽象类，不同的子类对<br>父类的抽象方法可以有不同的实现。</p>
<p>如父类为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape&#123;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>则其子类 Circle  有两种做法：</p>
<p>方案一：重写抽象方法 area( ),使方法得以实现<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class Circle extends Shape&#123;</span><br><span class="line">	public double r;</span><br><span class="line">	public Circle(double r)&#123;</span><br><span class="line">		this.r=r;</span><br><span class="line">	&#125;</span><br><span class="line">	public double area()&#123;</span><br><span class="line">		return(double)(3.14*r*r);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>方案二：子类 Circle  类也定义为抽象类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public abstract class Circle extends Shape&#123;</span><br><span class="line">	public double r;</span><br><span class="line">	public Circle(double r)&#123;</span><br><span class="line">		this.r=r;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>即使父类是具体的，但其子类也可以是抽象的。如  Object  是具体的，但可以创建<br>抽象子类。</p>
<p>abstract 方法不能用 static 和 private 修饰；对于类，不能同时用 final 和 abstract  修饰，因为 final 关键字使得类不可继承，而 abstract  修饰的类如果不可以继承将没有任何意义。两者放在一起，会起冲突</p>
<p>如以下用法都会引起编译器报错：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">static abstract double area();</span><br><span class="line"></span><br><span class="line">private abstract double area();</span><br><span class="line"></span><br><span class="line">abstract final class Shape()&#123;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>三：一个完整准确的抽象类例子</p>
<p>声明一个抽象类 Shape,有抽象成员方法  area()。Shape 派生出两个子类圆  Circle  类和矩形 Rectangle  类。Shape 里声明了抽象方法area(),该方法分别在两个子类里得到实<br>现。</p>
<p>代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">abstract public class Shape&#123;</span><br><span class="line">	abstract double area();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class Circle extends Shape&#123;</span><br><span class="line">	public double r;</span><br><span class="line">	Circle()&#123;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	public Circle(double r)&#123;</span><br><span class="line">		this.r=r;</span><br><span class="line">	&#125;</span><br><span class="line">	public double getR()&#123;</span><br><span class="line">		return r;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setR(double r)&#123;</span><br><span class="line">		this.r=r;</span><br><span class="line">	&#125;</span><br><span class="line">	public double area()&#123;</span><br><span class="line">		return(double)(3.14*r*r);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class Rectangle extends Shape&#123;</span><br><span class="line">	public double lenghth;</span><br><span class="line">	public double wide;</span><br><span class="line">	Rectangle()&#123;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	public Rectangle(double lenghth,double wide)&#123;</span><br><span class="line">		this.lenghth=lenghth;</span><br><span class="line">		this.wide=wide;</span><br><span class="line">	&#125;</span><br><span class="line">	public double getLenghth()&#123;</span><br><span class="line">		return lenghth;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setLenghth(double lenghth)&#123;</span><br><span class="line">		this.lenghth = lenghth;</span><br><span class="line">	&#125;</span><br><span class="line">	public double getWide()&#123;</span><br><span class="line">		return wide;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setWide(double wide)&#123;</span><br><span class="line">		this.wide=wide;</span><br><span class="line">	&#125;</span><br><span class="line">	public double area()&#123;</span><br><span class="line">		return lenghth*wide;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class Test&#123;</span><br><span class="line">	public static void main(Stirng[] args)&#123;</span><br><span class="line">		Circle c=new Circle(3.5);</span><br><span class="line">		Rectangle re=new Rectangle(6,5);</span><br><span class="line">		System.out.println(c.area());</span><br><span class="line">		System.out.println(re.area());</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接口中的内部类</p>
<p>我们在实际开发过程中，如果想要创建某些公共代码，使得它们可以被某个接口的所有<br>不同实现所共用，那么接口内部的嵌套类会显得很方便。</p>
<p>也就是说，在接口中可以含有内部类。</p>
<p>在这里，向大家展示接口中放置普通成员内部类和抽象成员内部类的情况。</p>
<p>首先创建接口，接口中定义了普通内部类 InnerClass 和抽象内部类  AbInnerClass</p>
<p>普通成员内部类的实例化</p>
<p>创建接口的实现类  ClassDemo</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public interface IOuterInterface&#123;</span><br><span class="line">	int TEMP=100;</span><br><span class="line">	void abMethod();</span><br><span class="line">	public default void deMethod()&#123;</span><br><span class="line">		System.out.println(&quot;默认&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	public static void stMethod()&#123;</span><br><span class="line">		System.out.println(&quot;静态&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	public class InnerClass&#123;</span><br><span class="line">		public void show()&#123;</span><br><span class="line">			System.out.println(&quot;&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	public abstract class AbInnerClass&#123;</span><br><span class="line">		public abstract void abInfo();</span><br><span class="line">		public void info()&#123;</span><br><span class="line">			System.out.println(&quot;&quot;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>普通成员内部类的实例化<br>创建接口的实现类  ClassDemo</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public class ClassDemo implements IOuterInterface&#123;</span><br><span class="line">	public void abMethod()&#123;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	public InnerClass getInner()&#123;</span><br><span class="line">		return new InnerClass();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class Test&#123;</span><br><span class="line">	public static void main(String[] args)&#123;</span><br><span class="line">		IOuterInterface.InnerClass inner=new IOuterInterface.InnerClass();</span><br><span class="line">		inner.show();</span><br><span class="line"></span><br><span class="line">		ClassDemo demo=new ClassDemo();</span><br><span class="line">		demo.getInner().show();</span><br><span class="line"></span><br><span class="line">		InnerClass innerTwo = new InnerClass();</span><br><span class="line">		innerTwo.show();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>抽象成员内部类的实例化<br>创建接口的实现类  AbClassDemo</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public class AbClassDemo implements IOuterInterface&#123;</span><br><span class="line">	public void abMethod()&#123;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">	public class AbDemo extends AbInnerClass&#123;</span><br><span class="line">		public void abInfo()&#123;</span><br><span class="line">			System.out.println();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">public class TestOne&#123;</span><br><span class="line"> public static void main(String[] args)&#123;</span><br><span class="line"> 	IOuterInterface.AbInnerClass abInner=new IOuterInterface.AbInnerClass()&#123;</span><br><span class="line"> 		public void abInfo()&#123;</span><br><span class="line"> 			System.out.println();</span><br><span class="line"> 		&#125;</span><br><span class="line"> 	&#125;;</span><br><span class="line"> 	aabInner.abInfo();</span><br><span class="line"> 	abInner.info();</span><br><span class="line"> 	System.out.println();</span><br><span class="line"></span><br><span class="line"> 	IOuterInterface.AbInnerClass abInner=new AbClassDemo().new AbDemo();</span><br><span class="line"> 	abInnerOne.abInfo();</span><br><span class="line"> 	abInnerOne.info();</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>匿名内部类详解</p>
<p>概  念</p>
<p>匿名内部类也就是没有名字的内部类正因为没有名字，所以匿名内部类只能使用一次，</p>
<p>它通常用来简化代码编写但使用匿名内部类还有个前提条件：</p>
<p>必须继承一个父类或实现一个接口</p>
<p>注意事项：</p>
<p>   编译后的文件命名：外部类$数字 . class<br>   无法使用 public、private、abstract、static  修饰，匿名内部类不能出现抽象方法<br>   无法编写构造方法，但可以添加构造代码块<br>   不能出现静态成员<br>   匿名内部类可实现接口也可以继承类，但是不可兼得<br>   匿名内部类不能是抽象的，它必须要实现继承的类或者实现接口的所有抽象方法</p>
<p>匿  名 内  部  类 初  始  化</p>
<p>我们一般都是利用构造器来完成某个实例的初始化工作的，但是匿名内部类是没有构造<br>器的，那怎么来初始化匿名内部类呢？使用构造代码块！利用构造代码块能够达到为匿名内<br>部类创建一个构造器的效果。<br>实例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public class OutClass&#123;</span><br><span class="line">	public InnerClass getInnerClass(final int age, final Stirng name)&#123;</span><br><span class="line">		return new InnerClass()&#123;</span><br><span class="line">			int age_;</span><br><span class="line">			Stirng name_;</span><br><span class="line">			&#123;</span><br><span class="line">				if(0&lt;age&amp;&amp;age&lt;200)&#123;</span><br><span class="line">					age_=age;</span><br><span class="line">					nam_=name;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">			public String getName()&#123;</span><br><span class="line">				return name_;</span><br><span class="line">			&#125;</span><br><span class="line">			public int getAge()&#123;</span><br><span class="line">				return age_;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">	&#125;</span><br><span class="line">	public static void main(String[] args)&#123;</span><br><span class="line">		OutClass out = new OutClass();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实  例<br>匿名内部类可以有不同的表现形式，下面用实例向大家展示一下：<br>继承式的匿名内部类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">abstract class Car&#123;</span><br><span class="line">	public abstract void drive();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Test&#123;</span><br><span class="line">	public static void main(String[] args)&#123;</span><br><span class="line">		Car car=new Car()&#123;</span><br><span class="line">			public void drive()&#123;</span><br><span class="line">				System.out.println(&quot;&quot;);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		car.drive();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">interface Vehicle&#123;</span><br><span class="line">	public void drive();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Test&#123;</span><br><span class="line">	public static void main(Stirng[] args)&#123;</span><br><span class="line">		Vehicle v=new Vehicle()&#123;</span><br><span class="line">			public void drive()&#123;</span><br><span class="line">				System.out.println();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		v.drive();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">abstract class Bar&#123;</span><br><span class="line">	void doStuff(Foo f)&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class BarOne extends Bar&#123;</span><br><span class="line">	void doStuff(Foo f)&#123;&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">interface Foo&#123;</span><br><span class="line">	void foo();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class Test&#123;</span><br><span class="line">	static void go()&#123;</span><br><span class="line">		Bar b = new BarOne();</span><br><span class="line">		b.doStuff(new Foo())&#123;</span><br><span class="line">			public void foo()&#123;</span><br><span class="line">				System.out.println();</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>thread  类的匿名内部类实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public class Demo&#123;</span><br><span class="line">	public static void main(String[] args)&#123;</span><br><span class="line">		Thread t = new Thread()&#123;</span><br><span class="line">			public void run()&#123;</span><br><span class="line">				for (int i=1;i&lt;=5;i++)&#123;</span><br><span class="line">					System.out.println();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		t.start();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Runnable  接口的匿名内部类实现：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public class Demo&#123;</span><br><span class="line">	public static void main(Stirng[] args)&#123;</span><br><span class="line">		Runnable r=new Runnable()&#123;</span><br><span class="line">			public void run()&#123;</span><br><span class="line">				for(int i=1;i&lt;=5;i++)&#123;</span><br><span class="line">					System.out.println();</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;;</span><br><span class="line">		Thread t=new Thread(r);</span><br><span class="line">		t.start();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>向上转型和动态绑定机制</p>
<p>知  识 梳  理</p>
<ol>
<li>向上转型的概念：</li>
</ol>
<p>向上转型又叫自动转型、隐式转型。向上转型就是父类引用指向子类实例，也就是子类<br>的对象可以赋值给父类的对象。</p>
<p>如：Animal dog=new Dog( );   //Dog 类是 Animal  类的子类</p>
<p>注：向上转型是安全的，因为任何子类都继承并接受了父类的方法。从例子中也可以理<br>解，所有的狗狗都属于狗的父类——动物，这是可行的，但是向下转型则不行，若说所<br>有的动物都是狗狗就不成立了。（所以向下转型要通过强制类型转换，后续章节中会讲<br>解）</p>
<p>2、向上转型的应用</p>
<p>1）当一个子类对象向上转型父类类型以后，就被当成了父类的对象，所能调用的方法会<br>减少，只能调用子类重写了父类的方法以及父类派生的方法（如 set()、get()方法），<br>而不能调用子类独有的方法。<br>例如：</p>
<p>对象实例化：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Pen pc = new Pencil();</span><br></pre></td></tr></table></figure></p>
<p>此时，调用方法调用时</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">pc.writing();</span><br><span class="line">pc.show();</span><br></pre></td></tr></table></figure>
<p>可以调用子类重写父类的方法 writing(),但调用子类独有的方法 show()时就是无效的</p>
<p>2）父类中的静态方法是不允许被子类重写的。</p>
<p>如父类 Pen 中含有静态方法 draw( )</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public static void draw()&#123;</span><br><span class="line">	System.out.println();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当子类 Pencil 中也定义同名方法时，此时 draw( )算 Pencil  类自己独有的方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public static void draw()&#123;</span><br><span class="line">	System.out.println();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>测试类中调用时：</p>
<p>返回结果为：</p>
<p>也就是实际上调用的是父类的静态方法 draw( )</p>
<p>知  识 扩  展</p>
<p>多态的实现可以通过向上转型和动态绑定机制来完成，向上转型实现了将子类对象向上<br>转型为父类类型，而动态绑定机制能识别出对象转型前的类型，从而自动调用该类的方法，<br>两者相辅相成。</p>
<p>动态绑定：</p>
<p>绑定就是将一个方法调用同一个方法所在的类连接到一起就是绑定。绑定分为静态绑定和动<br>态绑定两种。</p>
<p>静态绑定：在程序运行之前进行绑定（由编译器和链接程序完成的），也叫做前期绑定。</p>
<p>动态绑定：在程序运行期间由 JVM  根据对象的类型自动的判断应该调用哪个方法，也叫做<br>后期绑定。</p>
<p>静态绑定的例子：</p>
<p>如有一类 Human,它派生出来三个子类 Chinese 类、American 类和 British  类，三个<br>子类中都重写了父类中的方法    speak(  )：void,在测试类中用静态绑定的方式调用方法<br>speak( )。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Chinese c = new Chinese();</span><br><span class="line">c.speak();</span><br><span class="line"></span><br><span class="line">American a=new American();</span><br><span class="line">a.speak();</span><br><span class="line"></span><br><span class="line">British b=new British();</span><br><span class="line">b.speak();</span><br></pre></td></tr></table></figure></p>
<p>这种调用方式是在代码里指定的，编译时编译器就知道 c 调用的是 Chinese 的 speak(  ),a调用的是 American 的 speak( )。</p>
<p>动态绑定的例子：</p>
<p>如果我们在测试类中做以下改动：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Human[] human = new Human[5];</span><br></pre></td></tr></table></figure>
<p>此时，Human 类中随机生成 Chinese 类、American 类和 British  类的对象，编译器不能<br>根据代码直接确定调用哪个类中的 speak(  )方法，直到运行时才能根据产生的随机数 n  的值来确定  human[i]到底代表哪一个子类的对象，这样才能最终确定调用的是哪个类中的<br>speak( )方法，这就是动态绑定。</p>
<p>向下转型和 instanceof  运算符的应用</p>
<p>知  识 梳  理</p>
<p>一：向下转型</p>
<ol>
<li>向下转型</li>
</ol>
<p>向下转型是与向上转型相对的概念，它是用子类引用指向父类实例。</p>
<p>如：下图，在进行转换是会报错</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Animal a = new Dog();</span><br><span class="line">Dog d=a;</span><br></pre></td></tr></table></figure>
<p>这时就告诉我们向下转型不能自动转换，我们需要强转，所以向下转型又叫做强制类型<br>转换。</p>
<p>正确的转换语句为：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Animal a=new Dog();</span><br><span class="line">Dog d=(Dog)a;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>向下转型后，可以调用子类自己独有的方法。<br>例如：（承接上一文档例子）</li>
</ol>
<p>测试类中通过强制类型转换后，可调用 Pencil 类中独有的方法 show( )了。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Pen pc = new Pencil();</span><br><span class="line">Pencil p = (Pencil)pc;</span><br><span class="line">p.show();</span><br></pre></td></tr></table></figure></p>
<ol start="3">
<li>兄弟类之间不能进行强制类型转换。</li>
</ol>
<p>如：父类 Pen 类派生出另一个子类 Brush。</p>
<p>将指向 Brush 对象的父类引用 b 强制转换为 Brush 的兄弟类 Pencil  的对象，此时编译<br>器并没有报错，但在运行时会报出如下错误：</p>
<p>二：instanceof  运算符</p>
<p>1． 基本概念<br>instanceof  运算符用来判断对象是否可满足某个特定类型实例特征。返回值为<br>true/false。一般用于 if  语句中。</p>
<p>表示方法为：<br>如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">boolean result;</span><br><span class="line">Pen pc=new Pencil();</span><br><span class="line">result=pc instanceof Pencil;</span><br></pre></td></tr></table></figure>
<p>如果左边对象是右边类的实例则返回 true,否则返回 false。</p>
<p>2.instanceof  运算符的应用</p>
<p>1）用  instanceof  运算符用来判断对象是否可满足某个特定类型实例特征<br>例子：</p>
<p>父类 Parents 类，Father 类和 Mother  类分别为它的两个子类：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Parents f=new Father();</span><br><span class="line">Parents m=new Mother();</span><br></pre></td></tr></table></figure></p>
<p>运行结果为：<br>注：java 中所有类都直接或间接继承于 Object  类。</p>
<h2 id="Four"><a href="#Four" class="headerlink" title="Four"></a>Four</h2><p>依赖与关联关系</p>
<p>依赖关系<br>依赖关系(Dependency)  是一种使用关系，特定事物的改变有可能会影响到使用<br>该事物的其他事物，在需要表示一个事物使用另一个事物时使用依赖关系。如人要过河<br>时要使用到船，人与船之间就是依赖关系；我用锤子在墙上锤了一下，我和锤子之间就<br>是依赖关系；装修工人安装灯具时需要使用工具，装修工人和工具之间就是依赖关系。<br>大多数情况下，依赖关系体现在某个类的方法使用另一个类的对象作为参数。<br>依赖关系有下列三种情况：</p>
<p>A 类是 B  类中（某种方法的）局部变量<br>A 类是 B  类方法当中的一个参数<br>A 类向 B 类发送消息，从而影响 B  类发生变化</p>
<p>我们这里就依赖关系最常出现的情况—在某个类的方法使用另一个类的对象作为参数<br>进行举例说明：<br>课程表与课程之间就是依赖关系，<br>UML  图表示为：<br>对应的 java  代码片段：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">public class CourseTable&#123;</span><br><span class="line">	public void addCourse(Course course)&#123;</span><br><span class="line">		course.show();</span><br><span class="line">		System.out.println();</span><br><span class="line">	&#125;</span><br><span class="line">	public void reCourse(Course course)&#123;</span><br><span class="line">		course.show();</span><br><span class="line">		System.out.println();</span><br><span class="line">	&#125;</span><br><span class="line">	public class Course&#123;</span><br><span class="line">		public void show()&#123;</span><br><span class="line">			System.out.println();</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>课程表类中用课程的对象作为参数，进行增加课程和删除课程的功能。课程的变化<br>会引起课程表的实时变更，这就是一种“use a”的关系，也就是课程表依赖于课程。</p>
<p>关联关系</p>
<p>关联关系是类与类之间最常用的一种关系，它是一种结构化关系，代表类的对象之<br>间的一组连接。如客户与订单、老师与学生、公司与职员，人体与大脑，这些关系不是<br>是使用时才有的，而是一种长期且稳定的关系。<br>关联关系可以分为双向关联、单向关联、自关联。</p>
<p>a)<br>双向关联：<br>指双方都知道对方的存在，都可以调用对方的公共属性和方法。默认情况下，关<br>联是双向的。如供货商和顾客之间的关系，一家供货商可以向多个顾客供货，一个顾<br>客也可以向多家供货商进货</p>
<p>UML  图表示为：<br>对应的 java  代码片段：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class Customer&#123;</span><br><span class="line">	private Supplier[] supplier;</span><br><span class="line">	.....</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class Supplier&#123;</span><br><span class="line">	public Customer[] customer;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>b)<br>单向关联：<br>类的关联关系也可以是单向的，单向关联用带箭头的实线表示。例如：顾客<br>(Customer)拥有地址(Address)，则 Customer 类与 Address  类具有单向关联关系<br>UML  图表示为：</p>
<p>对应的 java  代码片段：<br>c)<br>自身关联（反身关联）：<br>在系统中可能会存在一些类的属性对象类型为该类本身，这种特殊的关联关系称<br>为自关联。顾客自身需要用到自己对象时，自己引用自己，带着一个自己的引用。<br>UML  图表示为：</p>
<p>对应的 java  代码片段：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class Customer&#123;</span><br><span class="line">	private Address address;</span><br><span class="line">	...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">public class Address&#123;</span><br><span class="line">	...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>补充扩展：<br>重数性关联:  表示一个类的对象与另一个类的对象连接的个数。<br>在 UML  中多重性关系可以直接在关联直线上增加一个数字表示与之对应的另一个类<br>的对象的个数。在关联的两端可写上一个被称为重数的范围，表示该类有多少个对象可与<br>对方一个对象连接，重数的默认值为 1，重数的符号通常有：<br>表示方式</p>
<p>多重性说明<br>表示“1”，表示另一个类的一个对象只与一个该类对象有关系<br>表示“零或多”，表示另一个类的一个对象与零个或多个该类对象有关系<br>表示“1 或多”，表示另一个类的一个对象与一个或多个该类对象有关系<br>表示“零或 1”，表示另一个类的一个对象没有或只与一个该类对象有关系<br>表示另一个类的一个对象与最少 m、最多 n 个该类对象有关系 (m&lt;=n)</p>
<p>ok</p>
      
    </div>
    
    
    

      <div>
        
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
        
      </div>

    

      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/微信公众号.jpg" alt="达叔小生 wechat" style="width: 200px; max-width: 100%">
    <div>欢迎您扫一扫上面的微信公众号，订阅我的博客！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="达叔小生 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    达叔小生
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://huangguangda.github.io/2018/05/08/1/" title="零基础入门Android语法与界面笔记">https://huangguangda.github.io/2018/05/08/1/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/我的视频/" rel="tag"><i class="fa fa-tag"></i> 我的视频</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/07/1/" rel="next" title="毕向东Java基础视频教程光碟01笔记">
                <i class="fa fa-chevron-left"></i> 毕向东Java基础视频教程光碟01笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/05/09/1/" rel="prev" title="制作个人简历模板网页效果 | 码云端的开源项目">
                制作个人简历模板网页效果 | 码云端的开源项目 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTU5OC8xMjEzNA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.gif" alt="达叔小生">
            
              <p class="site-author-name" itemprop="name">达叔小生</p>
              <p class="site-description motion-element" itemprop="description"></p>

            <div id="days"></div>
<script>
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("04/23/1997 00:00:00");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
                <a title="收藏到书签，偶尔High一下^_^" rel="alternate" class="mw-harlem_shake_slow wobble shake" href="javascript:(function() {
    function c() {
        var e = document.createElement(&quot;link&quot;);
        e.setAttribute(&quot;type&quot;, &quot;text/css&quot;);
        e.setAttribute(&quot;rel&quot;, &quot;stylesheet&quot;);
        e.setAttribute(&quot;href&quot;, f);
        e.setAttribute(&quot;class&quot;, l);
        document.body.appendChild(e)
    }
 
    function h() {
        var e = document.getElementsByClassName(l);
        for (var t = 0; t < e.length; t++) {
            document.body.removeChild(e[t])
        }
    }
 
    function p() {
        var e = document.createElement(&quot;div&quot;);
        e.setAttribute(&quot;class&quot;, a);
        document.body.appendChild(e);
        setTimeout(function() {
            document.body.removeChild(e)
        }, 100)
    }
 
    function d(e) {
        return {
            height : e.offsetHeight,
            width : e.offsetWidth
        }
    }
 
    function v(i) {
        var s = d(i);
        return s.height > e && s.height < n && s.width > t && s.width < r
    }
 
    function m(e) {
        var t = e;
        var n = 0;
        while (!!t) {
            n += t.offsetTop;
            t = t.offsetParent
        }
        return n
    }
 
    function g() {
        var e = document.documentElement;
        if (!!window.innerWidth) {
            return window.innerHeight
        } else if (e && !isNaN(e.clientHeight)) {
            return e.clientHeight
        }
        return 0
    }
 
    function y() {
        if (window.pageYOffset) {
            return window.pageYOffset
        }
        return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
    }
 
    function E(e) {
        var t = m(e);
        return t >= w && t <= b + w
    }
 
    function S() {
        var e = document.createElement(&quot;audio&quot;);
        e.setAttribute(&quot;class&quot;, l);
        e.src = i;
        e.loop = false;
        e.addEventListener(&quot;canplay&quot;, function() {
            setTimeout(function() {
                x(k)
            }, 500);
            setTimeout(function() {
                N();
                p();
                for (var e = 0; e < O.length; e++) {
                    T(O[e])
                }
            }, 15500)
        }, true);
        e.addEventListener(&quot;ended&quot;, function() {
            N();
            h()
        }, true);
        e.innerHTML = &quot; <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>&quot;;
        document.body.appendChild(e);
        e.play()
    }
 
    function x(e) {
        e.className += &quot; &quot; + s + &quot; &quot; + o
    }
 
    function T(e) {
        e.className += &quot; &quot; + s + &quot; &quot; + u[Math.floor(Math.random() * u.length)]
    }
 
    function N() {
        var e = document.getElementsByClassName(s);
        var t = new RegExp(&quot;\\b&quot; + s + &quot;\\b&quot;);
        for (var n = 0; n < e.length; ) {
            e[n].className = e[n].className.replace(t, &quot;&quot;)
        }
    }
 
    var e = 30;
    var t = 30;
    var n = 350;
    var r = 350;
    var i = &quot;//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake.mp3&quot;;
    var s = &quot;mw-harlem_shake_me&quot;;
    var o = &quot;im_first&quot;;
    var u = [&quot;im_drunk&quot;, &quot;im_baked&quot;, &quot;im_trippin&quot;, &quot;im_blown&quot;];
    var a = &quot;mw-strobe_light&quot;;
    var f = &quot;//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css&quot;;
    var l = &quot;mw_added_css&quot;;
    var b = g();
    var w = y();
    var C = document.getElementsByTagName(&quot;*&quot;);
    var k = null;
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            if (E(A)) {
                k = A;
                break
            }
        }
    }
    if (A === null) {
        console.warn(&quot;Could not find a node of the right size. Please try a different page.&quot;);
        return
    }
    c();
    S();
    var O = [];
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            O.push(A)
        }
    }
})()"><i class="fa fa-music"></i> High</a>

            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/huangguangda" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:2397923107@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/c785ece603d1" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-android"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_36232611" target="_blank" title="csdn">
                      
                        <i class="fa fa-fw fa-spinner"></i>csdn</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/186539024/" target="_blank" title="豆瓣">
                      
                        <i class="fa fa-fw fa-bath"></i>豆瓣</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/da-shu-xiao-sheng/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/5a16e1f3f265da43128096cb" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-google"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5507262458/profile?topnav=1&wvr=6" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1NTcxOTQ1Nw==&scene=124#wechat_redirect" target="_blank" title="历史">
                      
                        <i class="fa fa-fw fa-apple"></i>历史</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/dashucoding/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-facebook"></i>博客园</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gdone.gitee.io/englishpages/index.html" target="_blank" title="英文简历">
                      
                        <i class="fa fa-fw fa-globe"></i>英文简历</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gdone.gitee.io/pages/" target="_blank" title="中文简历">
                      
                        <i class="fa fa-fw fa-heartbeat"></i>中文简历</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/GDone/events" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-twitter"></i>码云</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://my.oschina.net/xiaomaomi1997/" target="_blank" title="开源中国">
                      
                        <i class="fa fa-fw fa-facebook"></i>开源中国</a>
                  </span>
                
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons">
              </a>
            </div>
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa fa-fw fa-globe"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="Web前端导航" target="_blank">Web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.36zhen.com/t?id=3448" title="前端书籍资料" target="_blank">前端书籍资料</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ife.baidu.com/" title="百度前端技术学院" target="_blank">百度前端技术学院</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://wf.uisdc.com/cn/" title="google前端开发基础" target="_blank">google前端开发基础</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.geekbang.org/" title="极客邦科技" target="_blank">极客邦科技</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ilxdh.com/" title="龙轩导航" target="_blank">龙轩导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://code.giffox.com/" title="程序员导航" target="_blank">程序员导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://search.chongbuluo.com/" title="快搜" target="_blank">快搜</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.android-doc.com/training/index.html" title="Android中文API" target="_blank">Android中文API</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://developer.android.google.cn/" title="Android Developers" target="_blank">Android Developers</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.freecodecamp.cn/" title="FreeCodeCamp中文社区" target="_blank">FreeCodeCamp中文社区</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://docs.oracle.com/javase/specs/" title="Java SE规范" target="_blank">Java SE规范</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://liuwangshu.cn/" title="刘望舒" target="_blank">刘望舒</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.colabug.com/author/3159ee71c93b3b4a/" title="小楼昨夜又秋风" target="_blank">小楼昨夜又秋风</a>
                  </li>
                
              </ul>

            </div>
          


        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#kage-和-import-的使用"><span class="nav-number">1.</span> <span class="nav-text">kage 和 import 的使用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Four"><span class="nav-number">2.</span> <span class="nav-text">Four</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="heart">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">达叔小生</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">357.6k</span>
  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共357.6k字</span>
</div>

<div class="weixin-box">
  <div class="weixin-menu">
    <div class="weixin-hover">
      <div class="weixin-description">微信扫一扫，订阅本博客</div>
    </div>
  </div>
</div>
        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>





  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=65809965";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  


  <script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script>
<script type="text/javascript" src="/js/src/custom.js"></script>


   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>


  <!-- 代码块复制功能 -->
  <script type="text/javascript" src="/js/src/clipboard.min.js"></script>  
  <script type="text/javascript" src="/js/src/clipboard-use.js"></script>
<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"live2d-widget-model-hibiki"},"display":{"position":"right","width":75,"height":150},"mobile":{"show":false},"log":false});</script></body>
</html>